package ck.mmd.dao;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import ck.mmd.bean.Remark;
import ck.mmd.util.DaoUtils;

public class RemarkDao {
	/**
	 * 通过自id查询单挑评论
	 * @param id 自己的id
	 * @return
	 */
	public Remark findRemarkById(String id) {
		String sql = "select * from remark where id = ?";
		try{
			QueryRunner runner = new QueryRunner(DaoUtils.getSource());
			return runner.query(sql,new BeanHandler<Remark>(Remark.class),id);
		}catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 通过所属id查询对应所有评论
	 * @param id 所属id
	 * @return 
	 */
	public List<Remark> findRemarksByUId(String id) {
		String sql = "select * from remark where last_id = ? order by uptime desc";
		try{
			QueryRunner runner = new QueryRunner(DaoUtils.getSource());
			return runner.query(sql, new BeanListHandler<Remark>(Remark.class),id);
		}catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 查询用户所有评论
	 * @param id
	 * @return
	 */
	public List<Remark> findRemarksByUserId(String id) {
		String sql = "select * from remark where user_id = ? order by uptime desc";
		try{
			QueryRunner runner = new QueryRunner(DaoUtils.getSource());
			return runner.query(sql, new BeanListHandler<Remark>(Remark.class),id);
		}catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public void deleteById(String id) {
		String sql = "delete from remark where id = ?";
		try{
			QueryRunner runner = new QueryRunner(DaoUtils.getSource());
			runner.update(sql, id);
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public void addRemark(Remark remark) {
		String sql = "insert into remark values(?,?,?,?,?,?,?,?)";
		try{
			QueryRunner runner = new QueryRunner(DaoUtils.getSource());
			runner.update(sql,remark.getId(),remark.getLast_id(),remark.getLast_title(),
					remark.getUser_id(),remark.getUser_name(),remark.getContent(),
					remark.getLikenum(),remark.getUptime());
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
